using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	public class ComboBox<TModel> : ComboBoxBase<ComboBox<TModel>, TModel> where TModel : class {
		public ComboBox(IModelViewHelper<TModel> helper, string memberName, string id = null) : base(helper, memberName, id) { }
	}

	public abstract class ComboBoxBase<T, TModel> : Selection<T, TModel>
		where T : ComboBoxBase<T, TModel>
		where TModel : class {
		protected ComboBoxBase(IModelViewHelper<TModel> helper, string memberName, string id = null) : base(helper, HtmlTag.Select, (id ?? memberName), memberName, false) { }

		protected override TagRenderMode TagRenderMode { get { return TagRenderMode.Normal; } }

		//protected override void SetId() {
		//    if (string.IsNullOrWhiteSpace(id)) base.Id(memberName);
		//    base.SetId();
		//}

		protected override void Prepare() {
			SetAttribute(HtmlAttribute.Single, HtmlAttribute.Single);
			base.Prepare();
		}

		private void AddOption(StringBuilder sb, KeyValuePair<object, string> option) {
			var item = new Option(option.Key, memberName);
			item.Selected(IsSelected(option.Key));
			sb.Append(item);
		}

		protected override string RenderOptions() {
			if (options == null) throw new ArgumentException("The control must have at least one option defined.", "Options");
			var sb = new StringBuilder();
			foreach (var option in options) AddOption(sb, option);
			return sb.ToString();
		}
	}
}